package net.maku.generator.controller;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import net.maku.generator.common.utils.Result;
import net.maku.generator.config.template.TemplateInfo;
import net.maku.generator.service.GeneratorService;
import net.maku.generator.domain.vo.PreviewVO;
import net.maku.generator.domain.vo.TreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * 代码生成
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("maku-generator/gen/generator")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     */
    @GetMapping("downloadZip")
    public void downloadZip(@RequestParam("tableIds") List<Long> tableIds, HttpServletResponse response) throws Exception {
        generatorService.downloadZip(tableIds, response);
    }

    /**
     * 生成代码（本地）
     */
    @GetMapping("downloadLocal")
    public Result<Void> downloadLocal(@RequestParam("tableId") Long tableId) {
        generatorService.downloadLocal(tableId);
        return Result.ok();
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview")
    public Result<List<PreviewVO>> preview(@RequestParam Long tableId) {
        List<PreviewVO> results = generatorService.preview(tableId);
        return Result.ok(results);
    }

    /**
     * 树形数据
     */
    @GetMapping("/tree-data")
    public Result<List<TreeVO>> treeData(@RequestParam("tableId") Long tableId) {
        List<TreeVO> results = generatorService.treeData(tableId);
        return Result.ok(results);
    }

    /**
     * 下载单个文件代码
     */
    @GetMapping("/download-template-content")
    public void download(@RequestParam("tableId") Long tableId,
                         @RequestParam("templateId") Long templateId,
                         HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        TemplateInfo templateInfo = generatorService.generatorCode(tableId, templateId);

        outputStream.write(templateInfo.getTemplateData().getBytes());
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + templateInfo.getFileName());
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

}